#!/bin/bash

set -euf -o pipefail

cmd="${1:-}"
replica="${2:-0}"
index="$HOME/.sourcegraph/zoekt/index-$replica"

if ((replica != 0)) && [[ -n "${DISABLE_SEARCH_SHARDING-}" ]]; then
    exit 0
fi

webport=$((3070 + replica))
indexport=$((6072 + replica))

# Mirroring:
# - https://github.com/sourcegraph/infrastructure/blob/d67cfdaf7760b926df165745e40f7bd9507d1c20/docker-images/zoekt-indexserver/Dockerfile#L28-L35
# - https://github.com/sourcegraph/infrastructure/blob/d67cfdaf7760b926df165745e40f7bd9507d1c20/docker-images/zoekt-webserver/Dockerfile#L27-L34
export GOGC=50

case "$cmd" in

indexserver)
    exec zoekt-sourcegraph-indexserver \
        -sourcegraph_url http://localhost:3090 \
        -index "$index" \
        -hostname "localhost:$webport" \
        -interval 1m \
        -listen ":$indexport" \
        -cpu_fraction 0.25
    ;;

webserver)
    exec env JAEGER_DISABLED=false zoekt-webserver -index "$index" -pprof -rpc -listen ":$webport"
    ;;

*)
    echo "USAGE: $0 (indexserver|webserver)"
    exit 1
    ;;

esac
